/*
 * The X-Minou Projet
 * X-Minou is a text, irc like chat program for
 * local users of Unix system
 *
 * Author :  RaX| <raxxx.fr@gmail.com>
 *
 * Xminou in a free software released as-is.
 */

#include <cstdlib>
#include <sys/stat.h>

#include "xminou_users.hh"
#include "xminou.hh"

UsersFile::UsersFile (void)
{

  m_file.open (USERS_FILE, std::fstream::app | std::fstream::ate);

  chmod (USERS_FILE, S_IWUSR
    | S_IRUSR
    | S_IWOTH
    | S_IROTH
    | S_IWGRP
    | S_IRGRP);

}

void
UsersFile::join (void)
{
   
  m_file << getpid()
       << ":"
       << whoami ()
       << std::endl;

}

void
UsersFile::part (void)
{

  int pid = getpid ();

  std::vector<std::string> v = who ();

  m_file.close ();
  m_file.open (USERS_FILE);

  m_file << "";

  for (unsigned int i = 0; i < v.size (); i++)
   {
    if (extract_line_pid (v.at (i)) != pid)
      m_file << v.at (i) << std::endl;    
   }  

}

std::vector<std::string>
UsersFile::who ()
{

  std::vector <std::string> v;

  std::ifstream file (USERS_FILE);
 
  while (!file.eof ())
   {
    std::string line;
    
    std::getline (file, line);
    if (!line.empty ())
      v.push_back (line);
   }

  file.close ();

  return v;

}

int
UsersFile::extract_line_pid (std::string line)
{

  return atoi (line.substr (0, line.find (":")).c_str ());

}

UsersFile::~UsersFile (void)
{

  m_file.close ();

}

